<template>
  <div class="courseStatistics">
    <courseHeadInfo :courseInfo="courseInfo" />
    <div class="main">
      <div style="display: flex;">
        <div style="margin-left: 10px">
          班级：
          <selectClassBtn :courseData="courseData" :defaultSelct="$route.query.filter" :collapseTags="true"
            @handleChange="handleChange" />
        </div>
        <div style="margin-left: 10px">
          <el-button @click="showMore" :disabled="loading" type="primary">查看更多</el-button>
        </div>
      </div>
      <div v-if="$route.params.id">
        <carouselEchartsBar :taskCount="taskCount" :finshCount="finshCount" :studyCount="studyCount"
          v-loading="loading" />
        <carouselEchartsLine :taskCount="taskCount" :finshCount="finshCount" :scoreCount="scoreCount"
          v-loading="loading" />
        <collapseEcharts v-for="(item, index) in courseInfo.content" :key="index" :index="index" :item="item"
          :studyCount="studyCount" :taskCount="taskCount" :finshCount="finshCount" :scoreCount="scoreCount"
          v-loading="loading" />
      </div>
      <div v-else>
        <h2>请选择课程</h2>
      </div>
    </div>
  </div>
</template>

<script>
const courseHeadInfo = () =>
  import("@/components/teacherPage/courseHeadInfo/courseHeadInfo");
const carouselEchartsBar = () =>
  import("@/components/carouselEcharts/carouselEchartsBar");
const carouselEchartsLine = () =>
  import("@/components/carouselEcharts/carouselEchartsLine");
const collapseEcharts = () =>
  import("@/components/collapseEcharts/collapseEcharts");
const selectClassBtn = () =>
  import("@/components/selectClass/component/selectClassBtn");
const selectCourse = () =>
  import("@/views/teacher/statistics/components/selectCourse");
import {
  getTaskdata,
  getalltaskdata,
  getquerydatabystu,
} from "@/request/teacher";
import { getCurriculumCourseInfo } from "@/request/courses";
import { formatCourseGroupTaskObj } from "@/util/courseData";
export default {
  components: {
    courseHeadInfo,
    carouselEchartsBar,
    carouselEchartsLine,
    collapseEcharts,
    selectClassBtn,
  },
  data() {
    return {
      // 课程信息
      courseInfo: {},
      // 任务统计
      taskCount: [],
      // 学习人数
      studyCount: 0,
      // 总分
      scoreTotal: 100,
      // 完成人数统计
      finshCount: {
        finishedStuCount: [], // 完成
        studyingStuCount: [], // 在学
        notStartStuCount: [], // 未学
      },
      // 分数统计
      scoreCount: {
        maxScore: [], // 最高分
        avgScore: [], // 平均分
        minScore: [], // 最低分
      },
      courseData: {},
      loading: false,
      currNo: null,
    };
  },
  async created() {
    // this.fetchCourseInfo({ id: Number(this.$route.query.courseID) });
    if (this.$route.params.id) {
      this.currNo = this.$route.params.id
      this.handelFetchLocalData();
    }
  },
  methods: {
    // 添加标签
    setTagsViewTitle(name) {
      if (this.$route.path === "/") return;
      const title = this.$route.meta.name;
      const courseName = name.name;
      const route = Object.assign({}, this.$route, {
        title: courseName ? courseName : ` ${title}-${this.$route.params.id}`,
      });
      this.$store.dispatch("tagsView/updateVisitedView", route);
    },
    // 获取课程详情
    async fetchCourseInfo(params) {
      return new Promise((resolve, reject) => {
        this.loading = true
        // const courseInfo = getCourseDetail(params);
        const currCourseInfo = getCurriculumCourseInfo({
          id: this.currNo,
        });
        Promise.all([currCourseInfo]).then((res) => {
          this.loading = false
          this.courseInfo = res[0].data.courseData;
          this.courseInfo.content = [];
          formatCourseGroupTaskObj(this.courseInfo, this);
          res[0].data.name = res[0].data.courseData.name;
          this.courseData = res[0].data;
          this.setTagsViewTitle({ name: this.courseInfo.name });
          resolve(res[0]);
        });
      });
    },
    // 统计所有学生的学习数据
    fetchTaskData(params) {
      return new Promise((resolve, reject) => {
        getalltaskdata(params).then((data) => {
          resolve({ errno: 0, data: data });
        });
      });
    },
    // 调取接口同步数据
    async handelFetchData(
      params = {
        currNo: Number(this.currNo),
        className: this.$route.query.filter
          ? this.$route.query.filter.indexOf("全部") !== -1
            ? undefined
            : this.$route.query.filter
          : undefined,
      }
    ) {
      if (params.className) {
        const classList = await this.$store.dispatch("class/gClassList");
        const findClass = classList.find(
          (item) => item.className == params.className
        );
        findClass && (params.classID = findClass.classID);
        delete params.className;
      }
      let courseInfo = await this.fetchCourseInfo();
      let courseData = this.fetchTaskData(params);
      this.loading = true
      Promise.all([courseInfo, courseData]).then((res) => {
        this.loading = false
        let data = res[1].data;

        if (res[0].errno === 0 && res[1].errno === 0) {
          this.courseInfo = res[0].data.courseData;
          this.handleInitAllData();

          // 将任务组统计
          this.courseInfo.content.forEach((item) => {
            item.tasks.forEach((titem) => {
              this.taskCount.push({
                value: titem.name,
                taskGroupID: item.taskGroupID,
                taskID: titem.taskID,
              });
            });
          });

          // 给任务初始化数据
          this.taskCount.forEach((item, index) => {
            // 遍历对象 将每一个key都遍历一遍 item.key为数组 将key的值设为
            Object.keys(this.finshCount).forEach((item) => {
              this.finshCount[item][index] = 0;
            });
            Object.keys(this.scoreCount).forEach((item) => {
              this.scoreCount[item][index] = 0;
            });
          });

          let countFinish = Object.assign({}, this.finshCount);
          let countScore = Object.assign({}, this.scoreCount);
          // 当课程没有数据时 重新赋默认值 触发图表的监听数据变化(watch)
          if (!data?.length) {
            this.studyCount = 0;
            this.finshCount = Object.assign({}, this.finshCount);
            this.scoreCount = Object.assign({}, this.scoreCount);
            this.handelSaveData();
            return;
          }
          // 查找所有的任务数据
          this.taskCount.forEach((item, index) => {
            let findGourp = data.filter((ritem) => {
              return ritem.taskID === item.taskID;
            });
            // 将所有的任务数据 以任务的索引值为基准赋值给对应属性
            if (findGourp.length) {
              findGourp.forEach((fitem) => {
                Object.keys(countFinish).forEach((oitem) => {
                  countFinish[oitem][index] = fitem[oitem];
                });

                Object.keys(countScore).forEach((oitem) => {
                  countScore[oitem][index] =
                    fitem[oitem] >= 0 ? fitem[oitem] : 0;
                  // if (fitem[oitem] != -8) {
                  // } else {
                  //   countScore[oitem][index] = null;
                  // }
                });
              });
              this.finshCount = countFinish;
              this.scoreCount = countScore;
            }
          });
          this.studyCount =
            data[0].finishedStuCount +
            data[0].studyingStuCount +
            data[0].notStartStuCount;
          this.handelSaveData();
        }
      });
    },
    // 获取本地数据
    async handelFetchLocalData() {
      // 获取当前时间
      let currTime = new Date().getTime();
      let tenMinute = 600000; // 10分钟
      // 获取本地数据
      // localStorage.setItem('echartsBarAllTaskCount', '[{"a":2}]')
      let getEchartsbarAllTaskCount = localStorage.getItem(
        "echartsBarAllTaskCount"
      );
      // 如果本地数据存在 转换JSON类型
      if (getEchartsbarAllTaskCount) {
        getEchartsbarAllTaskCount = JSON.parse(getEchartsbarAllTaskCount);
      } else {
        getEchartsbarAllTaskCount = [];
      }
      // 如果有数据在本地
      if (getEchartsbarAllTaskCount.length) {
        // 查找是否有匹配的数据
        let findEBCouDaAlTask = getEchartsbarAllTaskCount.filter((item) => {
          return item.currNo === Number(this.currNo);
        });
        // 如果有匹配的数据
        if (findEBCouDaAlTask.length) {
          if (currTime - findEBCouDaAlTask[0].setTime < tenMinute) {
            // 等待课程信息返回
            await this.fetchCourseInfo();
            this.$nextTick(() => {
              this.studyCount = findEBCouDaAlTask[0].studyCount;
              this.finshCount = findEBCouDaAlTask[0].finshCount;
              this.scoreCount = findEBCouDaAlTask[0].scoreCount;
              this.taskCount = findEBCouDaAlTask[0].taskCount;
            });
          } else {
            // 调取接口获取数据
            this.handelFetchData();
          }
        } else {
          // 调取接口获取数据
          this.handelFetchData();
        }
      } else {
        // 调取接口获取数据
        this.handelFetchData();
      }
    },
    // 将图表数据保存在本地
    handelSaveData() {
      // 获取本地数据
      let getEchartsbarAllTaskCount = localStorage.getItem(
        "echartsBarAllTaskCount"
      );
      // 如果本地数据存在 转换JSON类型
      if (getEchartsbarAllTaskCount) {
        getEchartsbarAllTaskCount = JSON.parse(getEchartsbarAllTaskCount);
      } else {
        getEchartsbarAllTaskCount = [];
      }
      // 如果有数据在本地
      if (getEchartsbarAllTaskCount.length) {
        // 查找是否有匹配的数据
        let findNotEBCouDaAlTask = getEchartsbarAllTaskCount.filter((item) => {
          return item.currNo !== Number(this.currNo);
        });
        findNotEBCouDaAlTask.push({
          currNo: Number(this.currNo),
          setTime: new Date().getTime(),
          studyCount: this.studyCount,
          taskCount: this.taskCount,
          finshCount: this.finshCount,
          scoreCount: this.scoreCount,
        });
        this.setLocalStorage(JSON.stringify(findNotEBCouDaAlTask));
      } else {
        this.setLocalStorage(
          JSON.stringify([
            {
              currNo: Number(this.currNo),
              setTime: new Date().getTime(),
              studyCount: this.studyCount,
              taskCount: this.taskCount,
              finshCount: this.finshCount,
              scoreCount: this.scoreCount,
            },
          ])
        );
      }
    },
    // 设置数据
    setLocalStorage(str) {
      localStorage.setItem("echartsBarAllTaskCount", str);
    },
    // 将本地数据重新赋值
    handelRefreshSetData() {
      // this.taskCount = this.taskCount
      // this.finshCount = this.finshCount
    },
    // 初始化所有数据
    handleInitAllData() {
      this.taskCount = [];
      this.studyCount = 0;
      this.finshCount = {
        finishedStuCount: [], // 完成
        studyingStuCount: [], // 在学
        notStartStuCount: [], // 未学
      };
      this.scoreCount = {
        maxScore: [], // 最高分
        avgScore: [], // 平均分
        minScore: [], // 最低分
      };
    },
    // 筛选班级
    async handleChange(val) {
      const { query, params, name } = this.$route;
      const { currNo, courseID } = query;
      await this.$router.push({
        name: name,
        query: { currNo: currNo, courseID: courseID, filter: val },
        params: params,
      });
      this.handelFetchData(); //本地筛选即可！！
    },
    showMore() {
      this.$router.push(`/teacher/sinfo/${this.courseData.currNo}?currNo=${this.courseData.currNo}&courseID=${this.courseData.courseID}`)
    }
  },
};
</script>

<style lang="stylus">
.courseStatistics {
  .main {
    padding-top: 10px;
    padding-bottom: 30px;
    margin: 0 auto;
    max-width: 1200px;
  }
}
</style>